﻿using System;
using System.ServiceModel;
using System.Threading.Tasks;

namespace ServerUtils
{
    public abstract class WCFClient<TClient>
        where TClient : ICommunicationObject /* to be able to call Close() and Abort() on the client */, new() /* to be able to instantiate the client */
    {
        public TResult Execute<TResult>(Func<TClient, TResult> func)
        {
            TClient client = this.GetClient();
            try
            {
                TResult result = func.Invoke(client);
                client.Close();
                return result;
            }
            catch
            {
                client.Abort();
                throw;
            }
        }

        public async Task<TResult> ExecuteAsync<TResult>(Func<TClient, Task<TResult>> func)
        {
            TClient client = this.GetClient();
            try
            {
                TResult result = await func.Invoke(client);
                client.Close();
                return result;
            }
            catch
            {
                client.Abort();
                throw;
            }
        }

        public void Execute(Action<TClient> action)
        {
            TClient client = this.GetClient();
            try
            {
                action.Invoke(client);
                client.Close();
            }
            catch
            {
                client.Abort();
                throw;
            }
        }

        public async Task ExecuteAsync(Func<TClient, Task> asyncAction)
        {
            TClient client = this.GetClient();
            try
            {
                await asyncAction.Invoke(client);
                client.Close();
            }
            catch
            {
                client.Abort();
                throw;
            }
        }

        protected virtual TClient GetClient() // virtual to allow a descendant to use the non-default constructor to pass parameters e.g. endpoint and remote address.
        {
            return new TClient();
        }
    }
}
